package com.flower.controller.farmer;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flower.annotation.Log;
import com.flower.domain.vo.farmer.FlowerEncyclopediaDetailVO;
import com.flower.domain.vo.farmer.FlowerEncyclopediaVO;
import com.flower.service.FlowerEncyclopediaService;
import com.flower.utils.AjaxResult;
import com.flower.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 花农端花卉百科
 */
@RestController
@RequestMapping("/encyclopedia")
@Slf4j
public class FlowerEncyclopediaController {
    
    @Autowired
    private FlowerEncyclopediaService encyclopediaService;
    
    /**
     * 分页查询花卉百科列表
     */
    @GetMapping("/list")
    public AjaxResult getEncyclopediaList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String family,
            @RequestParam(required = false) String genus,
            @RequestParam(required = false) Integer difficulty) {
        
        Map<String, Object> params = new HashMap<>();
        params.put("keyword", keyword);
        params.put("family", family);
        params.put("genus", genus);
        params.put("difficulty", difficulty);

        Page<FlowerEncyclopediaVO> pageResult = encyclopediaService.getEncyclopediaPage(page, pageSize, params);
        
        // 检查每个花卉是否有待审核的更新
        pageResult.getRecords().forEach(item -> {
            boolean hasUpdate = encyclopediaService.hasPendingUpdate(item.getId());
            item.setHasPendingUpdate(hasUpdate);
        });
        
        return AjaxResult.success(pageResult);
    }
    
    /**
     * 获取花卉百科详情
     */
    @GetMapping("/{id}")
    public AjaxResult getEncyclopediaDetail(@PathVariable Long id) {
        FlowerEncyclopediaDetailVO detailVO = encyclopediaService.getEncyclopediaDetail(id);
        if (detailVO == null) {
            return AjaxResult.error("未找到指定花卉信息");
        }
        return AjaxResult.success(detailVO);
    }
    
    /**
     * 获取待审核的花卉更新详情
     */
    @GetMapping("/{id}/pending")
    public AjaxResult getPendingUpdateDetail(@PathVariable Long id) {
        // 检查是否有待审核的更新
        if (!encyclopediaService.hasPendingUpdate(id)) {
            return AjaxResult.error("该花卉没有待审核的更新");
        }
        
        // 获取待审核的更新数据
        FlowerEncyclopediaDetailVO pendingDetail = encyclopediaService.getPendingEncyclopediaFromRedis(id);
        if (pendingDetail == null) {
            return AjaxResult.error("获取待审核的更新数据失败");
        }
        
        return AjaxResult.success(pendingDetail);
    }
    
    /**
     * 添加花卉百科
     */
    @Log(name = "添加花卉百科")
    @PostMapping()
    public AjaxResult addEncyclopedia(@RequestBody FlowerEncyclopediaDetailVO detailVO) {
        Long userId = UserContext.getUserId();
        Integer userType = 1; // 1:花农
        
        boolean result = encyclopediaService.addEncyclopedia(detailVO, userId, userType);
        
        if (result) {
            return AjaxResult.success("添加成功，等待审核");
        } else {
            return AjaxResult.error("添加失败，可能是花卉名称已存在");
        }
    }
    
    /**
     * 更新花卉百科
     */
    @Log(name = "更新花卉百科")
    @PutMapping("/{id}")
    public AjaxResult updateEncyclopedia(
            @PathVariable Long id,
            @RequestBody FlowerEncyclopediaDetailVO detailVO) {
        // 检查是否已有待审核的更新
        if (encyclopediaService.hasPendingUpdate(id)) {
            return AjaxResult.error("该花卉已有一个待审核的更新，请等待审核完成后再提交");
        }
        
        Long userId = UserContext.getUserId();
        Integer userType = 1; // 1:花农
        
        boolean result = encyclopediaService.updateEncyclopedia(id, detailVO, userId, userType);
        
        if (result) {
            return AjaxResult.success("更新已提交，等待审核");
        } else {
            return AjaxResult.error("更新失败，可能是花卉不存在或名称已被使用");
        }
    }
    
    /**
     * 删除花卉百科
     */
    @Log(name = "删除花卉百科")
    @DeleteMapping("/{id}")
    public AjaxResult deleteEncyclopedia(@PathVariable Long id) {
        boolean result = encyclopediaService.deleteEncyclopedia(id);
        
        if (result) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败，可能是花卉不存在");
        }
    }
    
    /**
     * 获取热门花卉百科
     */
    @GetMapping("/hot")
    public AjaxResult getHotEncyclopedias(
            @RequestParam(defaultValue = "6") Integer limit) {
        List<FlowerEncyclopediaVO> hotList = encyclopediaService.getHotEncyclopedias(limit);
        return AjaxResult.success(hotList);
    }
    
    /**
     * 更新浏览次数
     */
    @PutMapping("/{id}/view")
    public AjaxResult incrementViewCount(@PathVariable Long id) {
        encyclopediaService.incrementViewCount(id);
        return AjaxResult.success();
    }
    
    /**
     * 爬取花卉数据
     */
    @PostMapping("/crawl")
    public AjaxResult crawlFlowerData(@RequestParam String url) {
        boolean result = encyclopediaService.crawlFlowerData(url);
        
        if (result) {
            return AjaxResult.success("爬取成功");
        } else {
            return AjaxResult.error("爬取失败，请检查URL是否有效");
        }
    }
} 